package com.bobby.dao;

import com.bobby.utils.JdbcUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * @Description TODO
 * @Date 2020/8/13 9:40
 * @Created wenjunpei
 */
public abstract class BaseDao<T> {
    private QueryRunner queryRunner = new QueryRunner();

    private Class<T> type;

    public BaseDao() {
        Class  clazz =  this.getClass();
        Type genericSuperclass = clazz.getGenericSuperclass();
        ParameterizedType parameterizedType = (ParameterizedType) genericSuperclass;
        Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
        this.type = (Class<T>) actualTypeArguments[0];
    }

    public int update(String sql, Object ... params) throws SQLException {
        Connection connection = JdbcUtils.getConnection();

        return queryRunner.update(connection,sql,params);

    }

    public T queryForOne(String sql ,Object ... params ) throws SQLException {
        Connection connection = JdbcUtils.getConnection();
        BeanHandler beanHandler = new BeanHandler<T>(type);

        return (T) queryRunner.query(connection,sql,beanHandler,params);


    }

    public List<T> queryForList(String sql , Object ... params) throws SQLException {
        Connection connection = JdbcUtils.getConnection();
        BeanListHandler beanListHandler = new BeanListHandler<T>(type);

        return (List<T>) queryRunner.query(connection,sql,beanListHandler, params);

    }

    public Object queryForSingleValue(String sql,Object ... params) throws SQLException {
        Connection connection = JdbcUtils.getConnection();

        return queryRunner.query(connection,sql,new ScalarHandler(),params);

    }

}
